import React, { useState } from 'react';
import { 
  Form, 
  Input, 
  Button, 
  Card, 
  message, 
  Row,
  Col,
  Divider
} from 'antd';
import { 
  UserOutlined, 
  LockOutlined, 
  PhoneOutlined,
  UserAddOutlined,
  LoginOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { addUser, type AddUserParams } from '../api/userManagement';
import './Register.css';


const Register: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const navigate = useNavigate();

  // 处理注册
  const handleRegister = async (values: any) => {
    setLoading(true);
    try {
      const registerData: AddUserParams = {
        ...values,
        level: 2, // 默认设置为2级（操作员）
        user_perm: '' // 默认不给权限
      };
      
      const response = await addUser(registerData);
      if (response.code === 0) {
        message.success('注册成功！请联系管理员激活账户');
        setTimeout(() => {
          navigate('/login');
        }, 3000);
      } else {
        message.error(response.message || '注册失败');
      }
    } catch (error) {
      message.error('注册失败，请检查网络连接');
    } finally {
      setLoading(false);
    }
  };


  // 跳转到登录页
  const goToLogin = () => {
    navigate('/login');
  };


  return (
    <div className="register-container">
      <div className="register-background">
        <div className="register-content">
          <Card className="register-card">
            <div className="register-header">
              <div className="register-logo">
                <UserAddOutlined className="logo-icon" />
              </div>
              <h1 className="register-title">用户注册</h1>
              <p className="register-subtitle">User Registration</p>
            </div>

            <Form
              form={form}
              name="register"
              onFinish={handleRegister}
              autoComplete="off"
              size="large"
              layout="vertical"
            >
              <div className="step-content">
                <Row gutter={16}>
                  <Col span={24}>
                    <Form.Item
                      name="user"
                      label="用户名"
                      rules={[
                        { required: true, message: '请输入用户名' },
                        { pattern: /^[a-zA-Z0-9_]{3,20}$/, message: '用户名只能包含字母、数字、下划线，长度3-20位' }
                      ]}
                    >
                      <Input
                        prefix={<UserOutlined className="input-icon" />}
                        placeholder="请输入用户名"
                        autoComplete="username"
                      />
                    </Form.Item>
                  </Col>
                </Row>

                <Row gutter={16}>
                  <Col span={24}>
                    <Form.Item
                      name="name"
                      label="真实姓名"
                      rules={[{ required: true, message: '请输入真实姓名' }]}
                    >
                      <Input
                        prefix={<UserOutlined className="input-icon" />}
                        placeholder="请输入真实姓名"
                      />
                    </Form.Item>
                  </Col>
                </Row>
                
                <Row gutter={16}>
                  <Col span={24}>
                    <Form.Item
                      name="password"
                      label="密码"
                      rules={[
                        { required: true, message: '请输入密码' },
                        { min: 6, message: '密码长度至少6位' },
                        { pattern: /^(?=.*[a-zA-Z])(?=.*\d)/, message: '密码必须包含字母和数字' }
                      ]}
                    >
                      <Input.Password
                        prefix={<LockOutlined className="input-icon" />}
                        placeholder="请输入密码"
                        autoComplete="new-password"
                      />
                    </Form.Item>
                  </Col>
                </Row>

                <Row gutter={16}>
                  <Col span={24}>
                    <Form.Item
                      name="passwordv"
                      label="确认密码"
                      dependencies={['password']}
                      rules={[
                        { required: true, message: '请确认密码' },
                        ({ getFieldValue }) => ({
                          validator(_, value) {
                            if (!value || getFieldValue('password') === value) {
                              return Promise.resolve();
                            }
                            return Promise.reject(new Error('两次输入的密码不一致'));
                          },
                        }),
                      ]}
                    >
                      <Input.Password
                        prefix={<LockOutlined className="input-icon" />}
                        placeholder="请确认密码"
                        autoComplete="new-password"
                      />
                    </Form.Item>
                  </Col>
                </Row>

                <Row gutter={16}>
                  <Col span={24}>
                    <Form.Item
                      name="mobile"
                      label="手机号"
                      rules={[
                        { required: true, message: '请输入手机号' },
                        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
                      ]}
                    >
                      <Input
                        prefix={<PhoneOutlined className="input-icon" />}
                        placeholder="请输入手机号"
                      />
                    </Form.Item>
                  </Col>
                </Row>
              </div>

              <div className="step-actions">
                <Button 
                  type="primary" 
                  htmlType="submit"
                  loading={loading}
                  block
                >
                  注册
                </Button>
              </div>
            </Form>

            <Divider plain>已有账户？</Divider>
            
            <div className="register-footer">
              <Button
                type="default"
                icon={<LoginOutlined />}
                className="login-button"
                onClick={goToLogin}
                block
              >
                返回登录
              </Button>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
};

export default Register; 